package net.tycmc.cty.ctyms.timejob.iems.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DateControl;
import net.tycmc.cty.ctyms.timejob.common.LogUtil;
import net.tycmc.cty.ctyms.timejob.function.io.DownLoadNet;
import net.tycmc.cty.ctyms.timejob.iems.dao.WeatherInfoDAO;
import net.tycmc.cty.ctyms.timejob.iems.job.WeatherInfoJob;

import org.codehaus.jackson.map.ObjectMapper;

import java.net.URLEncoder;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import javax.crypto.Mac;  
import javax.crypto.SecretKey;  
import javax.crypto.spec.SecretKeySpec;  
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class WeatherInfoService {
	
	private static final String KEY_Code= "CWC_WeatherCode";
	private static final String KEY_CITY = "CWC_CityName";
	private static final String KEY_TEMP = "l1";
	private static final String KEY_Hum = "l2";
	private static final String KEY_WIND = "l3";
	private static final String KEY_WindDir = "l4";
	private static final String KEY_UpdateTime = "l7";
	
	private WeatherInfoDAO weatherInfoDAO;

	/**
	 * @return the weatherCatchDAO
	 */
	public WeatherInfoDAO getWeatherInfoDAO() {
		return weatherInfoDAO;
	}

	/**
	 * @param weatherCatchDAO the weatherCatchDAO to set
	 */
	public void setWeatherInfoDAO(WeatherInfoDAO weatherInfoDAO) {
		this.weatherInfoDAO = weatherInfoDAO;
	}
	
	private static List<Map<String,Object>> wInfoList = new ArrayList<Map<String,Object>>();
	private static List<Map<String,Object>> list2 = new ArrayList<Map<String,Object>>();
	private static List<Map<String,Object>> list3 = new ArrayList<Map<String,Object>>();
	
	public void catchWeather(){

		String date= DateControl.getDateTime(0);
		System.out.println("天气统计开始:"+date);
		
		String infoDate = DateUtil.addDay(0);
		List<Map<String,Object>> wCodeList = weatherInfoDAO.getWeatherCode_City();
		selectWeather(wCodeList,1);
		if(list2.size()>0){
			selectWeather(list2,2);
		}
		if(list3.size()>0){
			selectWeather(list3,3);
		}
		weatherInfoDAO.iWeatherInfo_City(wInfoList, infoDate);
		System.out.println("------------天气预报接口本次请求次数：-------------"+WeatherInfoJob.ReqTimes+"次");
		WeatherInfoJob.ReqTimes=0;//重置请求次数
		list2 = new ArrayList<Map<String,Object>>();
		list3 = new ArrayList<Map<String,Object>>();
		wInfoList = new ArrayList<Map<String,Object>>();
		System.out.println("天气统计结束:"+DateControl.getDateTime(0)+" ,执行时间(秒):"+DateControl.getMiaoShu(date,DateControl.getDateTime(0)));
	}
	
	public void selectWeather(List<Map<String,Object>> wCodeList,int i){
		if(WeatherInfoJob.ReqTimes==800){
			return ;
		}
		Map<String,Object> wSrcInfoMap = null;
		Map<String,Object> wInfoMap = null;
		String time=new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
		for(Map<String,Object> wCodeMap:wCodeList){
			//String netUrl = Test2.getInterfaceURL(MapGetter.getString(wCodeMap, KEY_Code), "observe");
			//String netUrl = Test2.getk780InterfaceURL(MapGetter.getString(wCodeMap, KEY_Code));
			String netUrl = Test2.get780InterfaceURL(MapGetter.getString(wCodeMap, KEY_Code));
			String wSrcInfo = DownLoadNet.downloadNetSimple(netUrl);
		    System.out.println(wSrcInfo);
			WeatherInfoJob.ReqTimes++;//请求次数增加1次
			wSrcInfoMap = JsonConvertMaps(wSrcInfo);
			if(null!=wSrcInfoMap&&"0".equals(MapGetter.getString(wSrcInfoMap,"status"))){//返回失败
				if(1 == i){
					list2.add(wCodeMap);
				}else if(2 == i){
					list3.add(wCodeMap);
				}else{
					
				}
				continue;
			}else{
				//wSrcInfoMap = JsonConvertMap(wSrcInfo);
				if(null == wSrcInfoMap)
					continue;
				wInfoMap = new HashMap<String,Object>();
				/*wInfoMap.put("CWI_CityName", MapGetter.getString(wCodeMap, KEY_CITY));
				wInfoMap.put("CWI_SrcInfo", wSrcInfo);
				wInfoMap.put("CWI_Temp", MapGetter.getString(wSrcInfoMap, KEY_TEMP));
				wInfoMap.put("CWI_Hum", MapGetter.getString(wSrcInfoMap, KEY_Hum));
				wInfoMap.put("CWI_Wind", MapGetter.getString(wSrcInfoMap, KEY_WIND));
				wInfoMap.put("CWI_WindDir", MapGetter.getString(wSrcInfoMap, KEY_WindDir));
				wInfoMap.put("CWI_UpdateTime", MapGetter.getString(wSrcInfoMap, KEY_UpdateTime));*/
				wInfoMap.put("CWI_CityName", MapGetter.getString(wSrcInfoMap,"city"));
				wInfoMap.put("CWI_SrcInfo",MapGetter.getString(wSrcInfoMap, "weather"));
				wInfoMap.put("CWI_Temp", MapGetter.getString(wSrcInfoMap, "temperature"));
				wInfoMap.put("CWI_Hum", MapGetter.getString(wSrcInfoMap,"humidity"));
				wInfoMap.put("CWI_Wind", MapGetter.getString(wSrcInfoMap,"windPower"));
				wInfoMap.put("CWI_WindDir", MapGetter.getString(wSrcInfoMap,"windDirection"));
				wInfoMap.put("CWI_UpdateTime", MapGetter.getString(wSrcInfoMap,"reportTime"));				
				wInfoList.add(wInfoMap);
			}
		}
	}
	/**将JSON串变成map
     * @param jsonStr
     * @return
     */
	  public Map<String, Object> JsonConvertMaps(String jsonStr) {
		  if(!StringUtil.isValid(jsonStr)){
			  return null;
		  }
			JSONObject json = JSONObject.fromObject(jsonStr);
			Map<String, Object> map = new HashMap<String, Object>();
			String status = json.getString("status");
			map.put("status",status);
			if (status.equals("true")) {
				String result = json.getString("weatherData");
				result = result.substring(1, result.length()-1);
				JSONObject  jsonobject = JSONObject.fromObject(result);
				Iterator it = jsonobject.keys();
				while (it.hasNext()) {
					String value="";
					String key = String.valueOf(it.next());
					if(jsonobject.get(key)==null||jsonobject.get(key).equals("null")){
					    value="";
					}else{
						value = (String) jsonobject.get(key);
					}
					map.put(key,value);									
				}

			}
			return map;
		}
	@SuppressWarnings("unchecked")
	public Map<String,Object> JsonConvertMap(String jsonStr){
		ObjectMapper objectMapper= new ObjectMapper();
		Map<String, Object> map1 = null;
		try {
			map1 = objectMapper.readValue(jsonStr,Map.class);
		} catch (Exception e) {
			//e.printStackTrace();
			LogUtil.info(this.getClass().getName(), "天气记录统计作业转换数据出错！");
			return null;
		}
		if(map1==null)return null;
		Map<String,Object> map2 = (Map<String,Object>)map1.get("l");
		return map2;
	}
//	@SuppressWarnings("unchecked")
//	public Map<String,Object> JsonConvertMap(String jsonStr){
//		ObjectMapper objectMapper= new ObjectMapper();
//		Map<String, Object> map1 = null;
//		try {
//			map1 = objectMapper.readValue(jsonStr,Map.class);
//		} catch (JsonParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (JsonMappingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		if(map1==null)return null;
//		Map<String,Object> map2 = (Map<String,Object>)map1.get("l");
//		return map2;
//	}
}

class Test2 {  
    private static final String MAC_NAME = "HmacSHA1";  
    private static final String ENCODING = "UTF-8";  
    private static final String appid = "f73c76ab36abaeb2";
    private static final String private_key = "a85366_SmartWeatherAPI_be7aa95";  
    private static final String url_header="http://open.weather.com.cn/data/?"; 
    //private static final String K780appkey = "17083";
    private static final String K780appkey = "18142";
    private static final String K780app = "weather.today";
    //private static final String K780sign = "14c961f6403c5986876d063038304f47";
    private static final String K780sign = "e40a83b1c961f1fd9e70c6f34cff5330";
    private static final String K780url_header="http://api.k780.com:80/?";  
    
    /** 
     * 使用 HMAC-SHA1 签名方法对对encryptText进行签名 
     *  
     * @param url 
     *            被签名的字符串 
     * @param privatekey 
     *            密钥 
     * @return 
     * @throws Exception 
     */  
    private static byte[] HmacSHA1Encrypt(String url, String privatekey)  
            throws Exception {  
        byte[] data = privatekey.getBytes(ENCODING);  
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称  
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);  
        // 生成一个指定 Mac 算法 的 Mac 对象  
        Mac mac = Mac.getInstance(MAC_NAME);  
        // 用给定密钥初始化 Mac 对象  
        mac.init(secretKey);  
        byte[] text = url.getBytes(ENCODING);  
        // 完成 Mac 操作  
        return mac.doFinal(text);  
    }  
    /** 
     * 获取URL通过privatekey加密后的码 
     * @param url 
     * @param privatekey 
     * @return 
     * @throws Exception 
     */  
    private static String getKey(String url, String privatekey) throws Exception {  
        byte[] key_bytes = HmacSHA1Encrypt(url, privatekey);  
        String base64encoderStr = Base64.encode(key_bytes);  
        return URLEncoder.encode(base64encoderStr, ENCODING);  
    }  
    /** 
     * 获得接口的URL地址 
     * @param areaid 
     * @param type 
     * @param date 
     * @return 
     * @throws Exception 
     */  
    private static String getInterfaceURL(String areaid,String type,String date) throws Exception{  
        String keyurl=url_header+"areaid="+areaid+"&type="+type+"&date="+date+"&appid=";  
        String key=getKey(keyurl+appid,private_key);  
        String appid6 = appid.substring(0, 6);  
          
        return keyurl+appid6+"&key=" + key;  
    }  
    /** 
     * 获得K780接口的URL地址 
     * @param areaid 
     * @param type 
     * @param date 
     * @return 
     * @throws Exception 
     */  
    public static String getk780InterfaceURL(String areaid){  
    	//netUrl = "http://api.k780.com:88/?app=weather.today&weaid=101010100&appkey=17082&sign=d3c841a578d220194cfb063459d68ad7&format=json";
        String keyurl=K780url_header+"app="+K780app+"&weaid="+areaid+"&appkey="+K780appkey+"&sign="+K780sign+"&format=json";  
    	//String keyurl="http://tytest.tygps.com/TYmapAPI/service/TYWeather?city=130100&key=07e0091a0e360204";
    	return keyurl;  
    }
    public static String get780InterfaceURL(String areaid){  
    	//netUrl = "http://api.k780.com:88/?app=weather.today&weaid=101010100&appkey=17082&sign=d3c841a578d220194cfb063459d68ad7&format=json";
        //String keyurl=K780url_header+"app="+K780app+"&weaid="+areaid+"&appkey="+K780appkey+"&sign="+K780sign+"&format=json";  
    	//http://mapapi.tygps.com/TYmapAPI/service/TYWeather?city=130100&key=07e0091a0e360204
    	String keyurl="http://mapapi.tygps.com/TYmapAPI/service/TYWeather?city="+areaid+"&key=07e0091a0e360204";
    	return keyurl;  
    }   
    public static String getInterfaceURL(String areaid,String type){  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmm");  
        String date = dateFormat.format(new Date());  
        try {  
            return getInterfaceURL(areaid,type,date);  
        } catch (Exception e) {  
        	e.printStackTrace();
        }  
        return null;  
    } 
    public static void main(String[] args) {
		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
	}
}  

